package com.googlecode.bip.dao;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import com.googlecode.bip.entity.ILocal;
import com.googlecode.bip.entity.Local;


/**
 *
 * @author Claude CHOISNET
 */
public class LocalDAO
      extends BipDAO
{
    private static final long serialVersionUID = 1L;
    private final static transient Logger slogger = Logger.getLogger( LocalDAO.class );
    private static transient Map<String,String> localMap;

    /**
     * Create a new LocalDB
     */
    public LocalDAO()
    {
    }

    /**
     *
     * @param idlocal
     * @return
     * @throws NamingException
     */
    public ILocal findLocal( final String idlocal )
        throws NamingException
    {
        return new Local( idlocal, getLocalMap().get( idlocal ) );
    }

    /**
     * UnsupportedOperationException
     * @param ilocal
     * @return
     */
    public boolean insertLocal( final ILocal ilocal )
    {
        throw new UnsupportedOperationException();
    }

    /**
     * UnsupportedOperationException
     * @param ilocal
     * @return
     */
    public boolean deleteLocal( final ILocal ilocal )
    {
        throw new UnsupportedOperationException();
    }

    /**
     * UnsupportedOperationException
     * @param ilocal
     * @return
     */
    public boolean updateLocal( final ILocal ilocal )
    {
        throw new UnsupportedOperationException();
    }

    /**
     * Returns an unmodifiable Map of (idlocal,name)
     * @return an unmodifiable Map of (idlocal,name)
     * @throws NamingException
     */
    public Map<String,String> getLocalMap() throws NamingException
    {
        if( localMap == null ) {
            loadLocalMap( getDataSource() );

            if( localMap == null ) {
                slogger.fatal( "Cant load 'local' table !!!!" );
                }
            }
        return Collections.unmodifiableMap( localMap );
    }

    /**
     * Returns an shadow copy of locale Map
     * @return an shadow copy of locale Map
     * @throws NamingException
     */
    public Map<String,String> getLocalMapClone()
        throws NamingException
    {
        return new HashMap<String,String>( getLocalMap() );
    }

    /**
     * Load local table in memory
     *
     * @param dataSource
     */
    synchronized private static void loadLocalMap( final DataSource dataSource )
    {
        localMap = DBHelper.getStringStringMap(
                dataSource,
                "SELECT * FROM `locals`",
                "idlocal",
                "name"
                );
    }

    /**
     * Use this when a new local entry is added
     */
    synchronized static void reset()
    {
        localMap = null;
    }
}
